/**
 * @context 用户登录
*/

import React, { createContext } from 'react';

// 登录上下文环境
export const AuthContext = createContext()

// 初始状态（未登录）
export const authInitiaStarte = {
  isAuthenticated: false,
  user: null,
  token: null
}

// 构建状态树
export const authReducer = (state, action) => {
  switch (action.type) {
    case "LOGIN":
      localStorage.setItem('user', JSON.stringify(action.payload.user))
      localStorage.setItem('token', JSON.stringify(action.payload.token))
      return {
        ...state,
        isAuthenticated: true,
        user: action.payload.user,
        token: action.payload.token
      }
    case "LOGOUT":
      return {
        ...state,
        isAuthenticated: false,
        user: null
      }
    default:
      return state
  }
}